package com.zjun.demo.experimentaldemo.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities


/**
 * Created by luyao
 * on 2018/3/13 16:16
 */
class NetWorkUtils {

    companion object{

        @SuppressLint("StaticFieldLeak")
        private lateinit var context: Context

        fun init(context: Context){
            if(context is Activity) {
                this.context = context.applicationContext
                return
            }
            this.context = context
        }

        /**
         * >= Android 10（Q版本）推荐
         *
         * NetworkCapabilities.NET_CAPABILITY_INTERNET，表示此网络应该(maybe)能够访问internet
         *
         * 判断当前网络可以正常上网
         * 表示此连接此网络并且能成功上网。  例如，对于具有NET_CAPABILITY_INTERNET的网络，这意味着已成功检测到INTERNET连接。
         */
        fun isConnectedAvailableNetwork(): Boolean {
            checkContextIsInitialized()
            val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val network = cm.activeNetwork ?: return false
            val capabilities = cm.getNetworkCapabilities(network) ?: return false
            return (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                    && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED))
        }

        private fun checkContextIsInitialized(){
            if(!this::context.isInitialized) throw Exception("尚未初始化")
        }

    }
}